<template>
  <view class="service-management">
    <!-- 导航栏 -->
   <!-- <uni-nav-bar 
      title="服务项目管理"
      :border="false"
      background-color="#fff"
    /> -->
    
    <!-- 分类导航 -->
    <view class="category-container">
      <uni-segmented-control 
        :current="activeCategory"
        :values="serviceCategories.map(item => item.label)"
        @clickItem="handleCategoryChange"
        style-type="text"
        active-color="#007AFF"
      />
    </view>
    
    <!-- 滑动视图 -->
    <swiper 
      :current="activeCategory"
      @change="onSwiperChange"
      :duration="300"
      class="service-swiper"
    >
      <!-- 每个分类的独立模块 -->
      <swiper-item v-for="(category, index) in serviceCategories" :key="index">
        <scroll-view scroll-y class="service-list">
          <!-- 服务项卡片 -->
          <view 
            v-for="service in filteredServices" 
            :key="service.id"
            class="service-card"
          >
            <view class="service-header">
              <text class="service-name">{{ service.name }}</text>
              <switch 
                :checked="service.status == 1"
                @change="val => toggleServiceStatus(service, val)"
                color="#007AFF"
              />
            </view>
            
            <!-- 展开详情 -->
            <view class="service-details" v-if="service.expanded">
              <view class="price-section">
                <uni-forms-item label="原价">
                  <input 
                    type="number" 
                    v-model="service.originalPrice"
                    placeholder="输入原价"
                  />
                </uni-forms-item>
                <uni-forms-item label="现价">
                  <input 
                    type="number" 
                    v-model="service.currentPrice"
                    placeholder="输入现价"
                  />
                </uni-forms-item>
              </view>
              
              <uni-forms-item label="服务介绍">
                <textarea 
                  v-model="service.description" 
                  placeholder="填写服务详情"
                />
              </uni-forms-item>
              
              <view class="action-buttons">
                <button class="btn-save" @click="saveService(service)">保存修改</button>
                <button 
                  class="btn-offline"
                  @click="handleOffline(service)"
                >下架服务</button>
              </view>
            </view>
            
            <view class="expand-trigger" @click="toggleExpand(service)">
              <uni-icons 
                :type="service.expanded ? 'arrowup' : 'arrowdown'" 
                size="20"
              />
            </view>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
    
    <!-- 套餐管理模块 -->
    <view class="package-section">
      <view class="section-header">
        <text>优惠套餐管理</text>
        <button class="btn-add" @click="showPackageForm(null)">
          <uni-icons type="plus" size="18" /> 新增套餐
        </button>
      </view>
      
      <view class="package-list">
        <view 
          v-for="pkg in currentCategoryPackages" 
          :key="pkg.id"
          class="package-card"
        >
          <view class="package-header">
            <text class="package-name">{{ pkg.name }}</text>
            <view class="package-actions">
              <uni-icons type="compose" @click="showPackageForm(pkg)" />
              <uni-icons type="trash" @click="deletePackage(pkg)" />
            </view>
          </view>
          <view class="package-content">
            <text>折扣率: {{ pkg.discount * 10 }}折</text>
            <text>包含服务: {{ pkg.services
			.map(sId => allServices.find(s => s.id === sId)?.name)
			.filter(name => name) // 过滤未找到的服务
			.join(', ') }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 套餐编辑弹窗 -->
   <uni-popup ref="packagePopup" type="center">
       <view class="package-form">
         <view class="form-header">
           <text>{{ isEditMode ? '编辑套餐' : '新建套餐' }}</text>
           <uni-icons type="close" @click="closeForm" />
         </view>
         
         <uni-forms ref="form" :modelValue="formData" :rules="formRules">
           <uni-forms-item label="套餐名称" name="name">
             <input v-model="formData.name" placeholder="请输入套餐名称" />
           </uni-forms-item>
           
           <uni-forms-item label="折扣率" name="discount">
             <view class="discount-input">
               <input 
                 v-model="formData.discount"
                 type="number"
                 step="0.1"
                 placeholder="0.1-1之间"
               />
               <text>折</text>
             </view>
           </uni-forms-item>
           
           <uni-forms-item label="选择服务" name="services">
             <view class="service-selector">
               <view 
                 v-for="service in availableServices"
                :key="service.id"
                class="service-tag"
                :class="{ selected: isServiceSelected(service.id),
						  disabled: service.status !== 1}"
                 @click="handleServiceSelect(service)"
               >
                 {{ service.name }}
				 <text v-if="service.status !== 1" class="status-tip">(已下架)</text>
               </view>
			   <view 
			    v-if="availableServices.length === 0" 
			    class="empty-tip"
			    >
			    当前分类无可选服务
			    </view>
             </view>
           </uni-forms-item>
      
         </uni-forms>
         
         <view class="form-actions">
           <button class="btn-cancel" @click="closeForm">取消</button>
           <button class="btn-submit" @click="submitForm">确认</button>
         </view>
       </view>
     </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { onReady } from '@dcloudio/uni-app'
import request from '../../utils/request'

// 新增状态定义
const packagePopup = ref(null)
const form = ref(null)
const isEditMode = computed(() => !!formData.id)

const categoryLabels = computed(() => {
  return serviceCategories.value.map(item => item.label);
});

// 服务分类字典
const serviceCategories = ref([]);
const activeCategory = ref(0)

const getAllServiceItem = async () =>  {
	request({
	  url: '/serviceItem/item/list',
	  method: 'get',
	  params: { 
	    page: 1,
	    size: 10
	  }
	}).then(res => {
	  console.log('请求成功:', res.rows);
	  services.value = res.rows.map(item => ({
	        id: item.serviceId, 
	        name: item.serviceName, 
	        originalPrice: item.originalPrice, 
	        currentPrice: item.currentPrice, 
	        description: item.serviceDesc, 
	        status: item.ext1 === "1" ? 1 : 0, // 后端字段 ext1，假设 ext1 为 "1" 表示启用
	        category: item.categoryId
	      }));
	  console.log('服务项目请求成功:', services.value);
	}).catch(err => {
	  console.error('请求失败:', err);
	});
}

const getAllServiceCategories = async () =>{
	request({
	  url: `/system/dict/data/type/service_category`,
	  method: 'get',
	}).then(res => {
	console.log('请求成功:', res);
	    if (res.code === 200 && res.data) {
	    // 假设 res.data 是返回的字典数据数组
	    const categoryMap = {};
	    res.data.forEach(item => {
	        categoryMap[item.dictCode] = item.dictLabel;
	    });
	    // 更新 serviceCategories
	    serviceCategories.value = Object.keys(categoryMap).map(key => ({
	        code: key,
	        label: categoryMap[key]
	    }));
	    console.log('serviceCategories 更新为:', serviceCategories.value);
	}
	}).catch(err => {
	  console.error('请求失败:', err);
	});
}

const getAllServicePackages = async () =>{
	try {
	    const res = await request({
	      url: '/serviceItem/package/list',
	      method: 'get',
	      params: { storeId: 1 }
	    });
	    
	    if (res.code === 200 && res.data) {
	      packages.value = res.data.map(pkg => ({
	        id: pkg.packageId,
	        name: pkg.packageName,
	        discount: pkg.discount,
	        // 取第一个服务的分类作为套餐分类（根据业务逻辑调整）
	        category: pkg.serviceItemList[0]?.categoryId || 0,
	        // 提取服务ID数组
	        services: pkg.serviceItemList.map(item => item.serviceId)
	      }));
	      console.log('套餐数据转换结果:', packages.value);
	    }
	  } catch (err) {
	    console.error('请求失败:', err);
	  }
}

onMounted(async () => {
  await getAllServiceCategories();
  await getAllServiceItem(); 
  await getAllServicePackages();
})

// 模拟数据
const services = ref([])

const packages = ref([])

// 套餐表单数据
const formData = reactive({
  id: null,
  category: null,
  name: '',
  discount: null,
  services: [],
})

// 新增计算属性
const allServices = computed(() => 
  services.value.filter(s => s.status == 1)
)

// 补充方法定义
const showPackageForm = (pkg) => {
  if (pkg) {
    formData.id = pkg.id
    formData.name = pkg.name
    formData.discount = pkg.discount
    formData.category = pkg.category
    formData.services = [...pkg.services] // 使用展开运算符避免引用问题
  } else {
    resetForm()
    formData.category = activeCategory.value // 绑定当前分类
  }
  packagePopup.value.open()
}

// 分类切换逻辑
const handleCategoryChange = (index) => {
	// console.log(index.currentIndex);
    activeCategory.value = index.currentIndex;
	// console.log(activeCategory.value);
};

const closeForm = () => {
  packagePopup.value.close()
  resetForm()
}

const resetForm = () => {
  formData.id = null
  formData.name = ''
  formData.discount = 0.9
  formData.services = []
  formData.expireDate = ''
}

// 补充切换服务状态方法
const toggleServiceStatus = async (service, e) => {
  // 保留原始值
  const originalStatus = service.status;
  const newStatus = originalStatus === 1 ? 0 : 1;
  
  // 立即更新 UI 状态但保留原始值副本
  service.status = newStatus;

  try {
    // 下架时需要检查
    if (newStatus === 0) {
      const checkRes = await request({
        url: `/serviceItem/item/checkInUse/${service.id}`,
        method: 'get'
      });
      
      if (checkRes.data) {
        uni.showToast({ title: '存在关联的未完成订单，无法下架', icon: 'none' });
        // 立即回滚状态
        service.status = originalStatus;
        return;
      }
    }

    // 发送状态更新请求
    const updateRes = await request({
      url: '/serviceItem/item/status',
      method: 'put',
      params: {
        serviceId: service.id,
        status: newStatus
      }
    });

    if (updateRes.code !== 200) {
      throw new Error(updateRes.msg || '更新失败');
    }
    
    uni.showToast({ title: '状态更新成功', icon: 'success' });
  } catch (error) {
    console.error('操作失败:', error);
    // 请求失败时回滚状态
    service.status = originalStatus;
    uni.showToast({ title: error.message || '操作失败', icon: 'none' });
  }
};


// 补充保存服务方法
const saveService = async (service) => {
  try {
    // 构造符合后端要求的请求体
    const requestData = {
      serviceId: service.id,
      originalPrice: Number(service.originalPrice),
      currentPrice: Number(service.currentPrice),
      serviceDesc: service.description
    }
	console.log(requestData)

    // 发送PUT请求
    const res = await request({
      url: '/serviceItem/item',
      method: 'put',
      data: requestData
    })

    // 处理响应
    if (res.code === 200) {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      })
      // 可选：更新本地数据
      Object.assign(service, {
        originalPrice: requestData.originalPrice,
        currentPrice: requestData.currentPrice,
        description: requestData.serviceDesc
      })
    } else {
      throw new Error(res.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    uni.showToast({
      title: error.message || '保存失败，请重试',
      icon: 'none',
      duration: 3000
    })
  }
}

// 补充展开切换方法
const toggleExpand = (service) => {
  service.expanded = !service.expanded
}

// 修复swiper切换方法
const onSwiperChange = (e) => {
  activeCategory.value = e.detail.current; // 确保是数字类型
};


// 表单验证规则
const formRules = reactive({
  name: {
    rules: [{ required: true, message: '请输入套餐名称' }]
  },
  discount: {
    rules: [
      { required: true, message: '请设置折扣率' },
      { 
        validateFunction: (rule, value, callback) => {
          if (value < 0.1 || value > 1) {
            callback('折扣率应在0.1-1之间')
          }
          return true
        }
      }
    ]
  },
  services: {
    rules: [{ required: true, message: '请至少选择一个服务项目' }]
  }
})

// 服务选择逻辑
const handleServiceSelect = (service) => {
  if (service.status !== 1) {
    uni.showToast({
      title: '该服务已下架，不可选择',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  toggleService(service.id);
}

const toggleService = (serviceId) => {
  formData.services = formData.services.includes(serviceId)
    ? formData.services.filter(id => id !== serviceId)
    : [...formData.services, serviceId];
};

const isServiceSelected = (serviceId) => {
  return formData.services.includes(serviceId)
}

// 表单提交
const submitForm = async () => {
  try {
    await form.value.validate()

    // 严格按照要求的格式构造数据
    const requestData = {
      packageName: formData.name,
      discount: Number(formData.discount),
      packageItems: formData.services.map(id => ({ serviceId: id })),
      storeId: 1 // 根据实际获取门店ID
    }

    // 如果是编辑操作需要添加packageId
    if (formData.id) {
      requestData.packageId = formData.id
    }

    // 发送请求
    const method = formData.id ? 'put' : 'post'
    const res = await request({
      url: '/serviceItem/package',
      method,
      data: requestData
    })

    if (res.code === 200) {
      uni.showToast({ title: '操作成功', icon: 'success' })
      await getAllServicePackages()
      closeForm()
    } else {
      throw new Error(res.msg || '操作失败')
    }
  } catch (e) {
    console.error('表单提交失败', e)
    uni.showToast({
      title: e.message || '操作失败',
      icon: 'none'
    })
  }
}

// 计算当前分类服务
const filteredServices = computed(() => {
  return services.value.filter(s => s.category === activeCategory.value);
});

// 下架服务方法
const handleOffline = async (service) => {
  const originalStatus = service.status;
  
  try {
    // 立即更新本地状态
    service.status = 0;
    
    // 检查是否存在关联订单
    const checkRes = await request({
      url: `/serviceItem/item/checkInUse/${service.id}`,
      method: 'get'
    });

    if (checkRes.data) {
      uni.showToast({
        title: '存在未完成订单，无法下架',
        icon: 'none',
        duration: 3000
      });
      service.status = originalStatus;
      return;
    }

    // 执行下架操作
    const updateRes = await request({
      url: '/serviceItem/item/status',
      method: 'put',
      params: {
        serviceId: service.id,
        status: 0
      }
    });

    if (updateRes.code !== 200) {
      throw new Error(updateRes.msg || '下架失败');
    }

    uni.showToast({
      title: '已成功下架',
      icon: 'success',
      duration: 2000
    });

  } catch (error) {
    console.error('下架操作失败:', error);
    service.status = originalStatus;
    uni.showToast({
      title: error.message || '下架失败，请重试',
      icon: 'none',
      duration: 3000
    });
  }
};

// 套餐删除校验
const deletePackage = async (pkg) => {
  try {
    // 确认弹窗
    const { confirm } = await uni.showModal({
      title: '删除套餐',
      content: `确定删除【${pkg.name}】套餐吗？此操作不可恢复！`,
      confirmColor: '#DD524D'
    })
    
    if (!confirm) return

    // 调用删除接口
    const res = await request({
      url: `/serviceItem/package/${pkg.id}`,
      method: 'delete'
    })

    if (res.code === 200) {
      uni.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 2000
      })
      // 两种更新方式任选其一：
      // 1. 本地删除（立即响应）
      packages.value = packages.value.filter(item => item.id !== pkg.id)
      // 2. 重新拉取数据（保证数据最新）
      await getAllServicePackages()
    } else {
      throw new Error(res.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除套餐失败:', error)
    // 处理业务规则错误
    const errorMap = {
      '未完成订单': '存在关联的未完成订单，无法删除',
      '套餐不存在': '该套餐已被删除'
    }
    const defaultMsg = '删除失败，请稍后重试'
    
    uni.showToast({
      title: errorMap[error.message],
      icon: 'none',
      duration: 3000
    })
  }
}

const currentCategoryPackages = computed(() => {
  return packages.value.filter(p => p.category == activeCategory.value)
})

const availableServices = computed(() => {
  return services.value.filter(
    s => s.status === 1 && s.category === formData.category
  )
})
</script>

<style lang="scss" scoped>
// 高级视觉样式
.service-management {
  background: #f5f7fa;
  min-height: 100vh;
}

.category-container {
  background: #fff;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.service-card {
  background: #fff;
  margin: 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
  overflow: hidden;
  
  .service-header {
    display: flex;
    justify-content: space-between;
    padding: 32rpx;
    align-items: center;
  }
  
  .service-name {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }
}

.package-card {
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  margin: 24rpx;
  padding: 32rpx;
  border-radius: 16rpx;
  border: 1px solid #eee;
  
  .package-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
  }
  
  .package-name {
    font-size: 28rpx;
    font-weight: 600;
    color: #2c3e50;
  }
}

.btn-add {
  background: linear-gradient(135deg, #007AFF, #0051ff);
  color: #fff;
  border-radius: 48rpx;
  padding: 0 16rpx;
  height: 64rpx;
  line-height: 64rpx;
  font-size: 26rpx;
  
  &::after {
    border: none;
  }
}

// 交互动效
.service-card {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }
}

.expand-trigger {
  background: #f8f9fa;
  padding: 16rpx;
  text-align: center;
  border-top: 1px solid #eee;
}

.package-form {
  background: #fff;
  width: 80vw;
  border-radius: 24rpx;
  padding: 32rpx;
  
  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32rpx;
    
    text {
      font-size: 36rpx;
      font-weight: 500;
    }
  }
}

.service-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  
  .empty-tip {
      color: #999;
      text-align: center;
      padding: 32rpx;
    }
  
  .service-tag {
    padding: 12rpx 24rpx;
    border: 1px solid #eee;
    border-radius: 24rpx;
    transition: all 0.2s;
    
    &.selected {
      background: #007AFF;
      color: #fff;
      border-color: transparent;
    }
  }
}

.discount-input {
  display: flex;
  align-items: center;
  
  input {
    flex: 1;
    margin-right: 16rpx;
  }
}

.form-actions {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 24rpx;
  margin-top: 48rpx;
  
  button {
    height: 60rpx;
	line-height: 60rpx;
    border-radius: 48rpx;
    font-size: 28rpx;
	text-align: center;
    
    &.btn-submit {
      background: linear-gradient(135deg, #007AFF, #0051ff);
	  border-radius: 12rpx;
      color: #fff;
    }
    
    &.btn-cancel {
      background: #f0f0f0;
	  border-radius: 12rpx;
      color: #666;
    }
  }
}

.service-swiper {
  height: 50vh; /* 根据实际需要调整 */
  background: #fff;
}

.service-list {
  height: 100%;
}

.service-details {
  background: #f8f9fa;
  padding: 24rpx;
  border-radius: 16rpx;
  margin: 0 32rpx;
  border: 1px solid #e8e8e8;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.1);
    transform: translateY(-4rpx);
  }
}

.price-section {
  padding: 0rpx;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 32rpx;
  margin-bottom: 32rpx;
  
  .uni-forms-item {
    background: #fff;
    padding: 24rpx;
    border-radius: 12rpx;
    border: 1px solid #eee;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
  }
  
  .uni-forms-item__label {
    color: #333;
    font-weight: 500;
  }
  
  input {
    border: none;
    border-radius: 12rpx;
    background: #f5f7fa;
    font-size: 28rpx;
    color: #333;
  }
}

.uni-forms-item[role="group"] {
  background: #fff;
  padding: 24rpx;
  border-radius: 16rpx;
  border: 1px solid #eee;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
  
  textarea {
    border: none;
    padding: 16rpx;
    border-radius: 12rpx;
    background: #f5f7fa;
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
  }
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 32rpx;
  
  button {
    flex: 1;
    margin: 0 8rpx;
    height: 64rpx;
    line-height: 64rpx;
    border-radius: 32rpx;
    font-size: 26rpx;
    border: none;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
  }
  
  .btn-save {
    background: linear-gradient(135deg, #007AFF, #0051ff);
    color: #fff;
    
    &:active {
      transform: scale(0.98);
      opacity: 0.9;
    }
  }
  
  .btn-offline {
    background: #f0f0f0;
    color: #666;
    
    &:active {
      transform: scale(0.98);
      opacity: 0.8;
    }
  }
}

.service-tag {
  &.disabled {
    background-color: #f5f5f5;
    color: #999;
    border-color: #e0e0e0;
    cursor: not-allowed;
    
    &.selected {
      background-color: #ffece8;
      color: #ff4d4f;
    }
  }
}

.status-tip {
  font-size: 24rpx;
  color: #ff4d4f;
  margin-left: 8rpx;
}

.delete-icon {
  transition: transform 0.2s ease;
  
  &:active {
    transform: scale(1.2);
    color: #dd514d !important;
  }
}

// 增加删除警告色
.uni-icons[type="trash"] {
  color: #999;
  
  &:active {
    color: #dd514d;
  }
}
</style>